﻿#include "ctestaudioplay.h"
#include "ui_ctestaudioplay.h"
#include <QUrl>
#include <QFileDialog>

CTestAudioPlay::CTestAudioPlay(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CTestAudioPlay)
{
    ui->setupUi(this);
    this->setWindowTitle("音乐播放器");

    m_pPlayer = new QMediaPlayer;
//    ui->btnPlay->setEnabled(false);

    m_pPlayer->setMedia(QUrl("123.mp3"));
    connect(m_pPlayer, &QMediaPlayer::mediaStatusChanged, this, [this](QMediaPlayer::MediaStatus status){
        if ( status == QMediaPlayer::EndOfMedia )
        {
            qDebug()<<"start play.";
            m_pPlayer->play();
        }
    });
}

CTestAudioPlay::~CTestAudioPlay()
{
    delete ui;
}

void CTestAudioPlay::on_btnPlay_clicked()
{
    //如果没有在播放
    if(this->isPlay)
    {
        m_pPlayer->pause();
        ui->btnPlay->setText(tr("播放"));
        this->isPlay = !this->isPlay;
    }
    else  //如果没有在播放
    {
        m_pPlayer->play();
        qDebug("voi play");
        ui->btnPlay->setText(tr("暂停"));
        this->isPlay = !this->isPlay;
    }
}

void CTestAudioPlay::on_btnStop_clicked()
{
    //如果没有在播放
    if(this->isPlay)
    {
        m_pPlayer->stop();
        qDebug("voi stop");
        ui->btnPlay->setText(tr("播放"));
        this->isPlay = !this->isPlay;
    }
}

void CTestAudioPlay::on_btnSelect_clicked()
{
    //筛选文件，只能选择mp3或wav格式的文件
    QUrl path = QFileDialog::getOpenFileUrl(this, tr("请选择音乐"), QUrl("c:/"), "music(*.mp3 *.wav)" );

    //选取文件后自动播放
    if(!path.isEmpty())
    {
        qDebug("file ready");
        m_pPlayer->setMedia(path);
        ui->btnPlay->setEnabled(true);

        ui->name->setText(path.toString());
        m_pPlayer->play();
        qDebug("voi play");
        ui->btnPlay->setText(tr("暂停"));
        this->isPlay = !this->isPlay;
    }
}
